package com.itwxz.forum.controller.common;


import cn.dev33.satoken.annotation.SaIgnore;
import com.itwxz.common.config.QiNiuConfig;
import com.itwxz.common.core.controller.BaseController;
import com.itwxz.common.core.domain.QiNiu;
import com.itwxz.common.core.domain.R;
import com.qiniu.storage.BucketManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/forum/mobile/qiniu")
public class ForumQiniuController extends BaseController {
    @Autowired
    private QiNiuConfig qiNiuConfig;


    /**
     * 自定义 qiniu 服务器上传请求
     */
    @GetMapping("/token")
    public R<QiNiu> uploadFileQiNiu() {
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());

        long expireSeconds = 600L; // 有效期 5 分钟（单位：秒）
        String upToken = auth.uploadToken(qiNiuConfig.getBucket(), null, expireSeconds, null);
        // log.info(upToken);
        return R.ok(QiNiu.builder()
                .token(upToken)
                .domain(qiNiuConfig.getDomain())
                .avatar(qiNiuConfig.getAvatar())
                .photo(qiNiuConfig.getPhoto())
                .forum(qiNiuConfig.getForum())
                .uuid(UUID.randomUUID().toString())
                .build()
        );
    }

    @GetMapping("/url")
    @SaIgnore
    public R<String> getAvatarUrl(String url) {
        if (StringUtils.isBlank(url)) return R.fail("不存在图片");

        String domain = qiNiuConfig.getDomain();
        String encodedFileName;
        try {
            encodedFileName = URLEncoder.encode(url, StandardCharsets.UTF_8).replace("+", "%20");
        } catch (Exception e) {
            return R.fail("头像编码失败");
        }
        String publicUrl = String.format("%s/%s", domain, encodedFileName);

        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        long expireInSeconds = 3600; // 链接有效期1小时
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);

        return R.ok(finalUrl);
    }
}
